﻿using HAF.LogUtility;
using SoapNotify.Assistantor;
using System;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SoapNotify
{
    public partial class FrmSoapMain : Form
    {
        public FrmSoapMain()
        {
            InitializeComponent();
        }

        private long getLongId()
        {
            byte[] bytes = Guid.NewGuid().ToByteArray();
            return BitConverter.ToInt64(bytes, 0);
        }
        private void btnSend_Click(object sender, EventArgs e)
        {
            string dateStr = DateTime.Now.ToString("yyyyMM/dd");
            GetDate(dateStr);

            string pushUrl = txtSoapUrl.Text;
            string cspid = txtCSPID.Text;
            string lspid = txtLSPID.Text;
            string tmpXml = txtTemplate.Text;
            string correlateId = txtCorrelateId.Text; // ;getLongId().ToString()
            string pushResult = txtResult.Text;
            string soapXml = txtFtpurl.Text;
            
            //switch (cmbType.SelectedIndex)
            //{
            //    case 0:
            //        InjectionXml(cspid, lspid, tmpXml, correlateId, soapXml, pushUrl);
            //        break;
            //    default:
            //        NotifyXml(cspid, lspid, tmpXml, correlateId, pushUrl, int.Parse(pushResult), soapXml);
            //        break;
            //}
        }

        private DateTime GetDate(string PubDateStr)
        {
            DateTime value = DateTime.Now;
            if (!string.IsNullOrEmpty(PubDateStr))
            {
                string[] tmpStr = PubDateStr.Split('/');
                string year, mouth, day = string.Empty;
                if (tmpStr.Length == 2)
                {
                    if (tmpStr[0].Length == 6 && tmpStr[1].Length == 2)
                    {
                        year = tmpStr[0].Substring(0, 4);
                        mouth = tmpStr[0].Substring(4, 2);
                        day = tmpStr[1];

                        string dateTmpStr = string.Concat(year, "-", mouth, "-", day);
                        value = DateTime.Parse(dateTmpStr);
                    }
                }
            }
            return value;
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            //cmbType.SelectedIndex = 0;
            cmbPostType.SelectedIndex = 0;

            ShowClear();
        }

        #region 消息输出
        private void ShowPopTips(string message)
        {
            MessageBox.Show(message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        int _msgLen = 0;

        private void ShowClear()
        {
            txtMsg.Clear();
        }

        private void ShowMessage(string msg)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action<string>(ShowMessage), msg);
            }
            else
            {
                if (_msgLen >= 300)
                {
                    txtMsg.Clear();
                    //txtMessages.Text = "";
                    _msgLen = 0;
                }
                LogHelper.WriteDebugLogExt("SysMonitor", msg);

                txtMsg.Text = txtMsg.Text + (DateTime.Now.ToString() + " " + msg + "\r\n");
                txtMsg.SelectionStart = txtMsg.Text.Length;
                txtMsg.ScrollToCaret();

                _msgLen++;

            }
        }

        #endregion 消息输出

        private void btnExit_Click(object sender, EventArgs e)
        {
            Environment.Exit(0);
        }

        /// <summary>
        /// 注入工单
        /// </summary>
        /// <param name="csid">上游ID</param>
        /// <param name="lsid">下游ID</param>
        /// <param name="correlateId">流水号</param>
        /// <param name="soapurl">下游注入服务地址</param>
        /// <param name="ftpurl">工单下载地址</param>
        /// <param name="templateXml">soap模板</param>
        private void InjectionXml(string cspid, string lspid, string tmpXml, string correlateId, string ftpurl, string soapurl)
        {
            string soapXml = string.Empty;
            string templateXml = Path.Combine(Environment.CurrentDirectory, "Template", tmpXml);
            using (FileStream fsread = new FileStream(templateXml, FileMode.Open, FileAccess.Read))
            {
                int buffLength = 1024;
                byte[] buffer = new byte[buffLength];
                //byte[] buffer = new byte[1024 * 1024 * 2];    //定义一个2M的字节数组
                int r = fsread.Read(buffer, 0, buffer.Length);    //每次读取1024字节放到字节数组里面
                                                                  //将字节数组中每一个元素按照指定的编码格式解码成字符串
                soapXml = Encoding.UTF8.GetString(buffer, 0, r);
                fsread.Close();
                //fsread.Dispose();
                soapXml = soapXml.Replace("{cspid}", cspid)
                    .Replace("{lspid}", lspid)
                    .Replace("{correlateid}", correlateId)
                    .Replace("{requestxml}", ftpurl);

                ShowMessage(string.Format("提交注入SOAP-XML：{0}", soapXml));
            }

            string rtn = WebHelper.PushNotifyRequest(soapurl, "POST", soapXml, Encoding.UTF8);
            ShowMessage(rtn);
        }

        /// <summary>
        /// 回执工单
        /// </summary>
        /// <param name="csid">上游ID</param>
        /// <param name="lsid">下游ID</param>
        /// <param name="correlateId">流水号</param>
        /// <param name="soapurl">下游注入服务地址</param>
        /// <param name="ftpurl">工单下载地址</param>
        /// <param name="templateXml">soap模板</param>
        private void NotifyXml(string cspid, string lspid, string templateXml, string correlateId, string soapurl, int result = 0, string ftpurl = "")
        {
            ShowMessage(correlateId);
            ShowMessage(soapurl);

            string soapXml = string.Empty;
            using (FileStream fsread = new FileStream(templateXml, FileMode.Open, FileAccess.Read))
            {
                int buffLength = 1024;
                byte[] buffer = new byte[buffLength];
                //byte[] buffer = new byte[1024 * 1024 * 2];    //定义一个2M的字节数组
                int r = fsread.Read(buffer, 0, buffer.Length);    //每次读取1024字节放到字节数组里面
                                                                  //将字节数组中每一个元素按照指定的编码格式解码成字符串
                soapXml = Encoding.UTF8.GetString(buffer, 0, r);
                //fsread.Close();
                //fsread.Dispose();
                soapXml = soapXml.Replace("{cspid}", cspid)
                    .Replace("{lspid}", lspid)
                    .Replace("{correlateid}", correlateId)
                    .Replace("{resultcmd}", result.ToString())
                    .Replace("{backxml}", ftpurl);

                ShowMessage(string.Format("提交回馈SOAP-XML：{0}", soapXml));
            }

            string rtn = WebHelper.PushNotifyRequest(soapurl, "POST", soapXml, Encoding.UTF8);
            ShowMessage(rtn);
        }

        private void btnPatchNotify_Click(object sender, EventArgs e)
        {
            string pushUrl = txtSoapUrl.Text;
            string cspid = txtCSPID.Text;
            string lspid = txtLSPID.Text;
            
            string correlateId = txtCorrelateId.Text; // ;getLongId().ToString()
            string pushResult = txtResult.Text;
            string soapXml = txtFtpurl.Text;
            string tmpXml = txtTemplate.Text;
            string tempXmlPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, tmpXml);
            if (!File.Exists(tempXmlPath))
            {
                ShowMessage("SOAP消息模板文件不存在，请检查");
                return;
            }
            
            //第一步：根据文件地址获取所有流水号
            string tmpStr = txtPatchFileAddress.Text;
            if (!string.IsNullOrEmpty(tmpStr))
            {
                string patchPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, tmpStr);
                if (File.Exists(patchPath))
                {
                    ShowMessage("*****************************************");
                    ShowMessage("启动批量回执任务");
                    ShowMessage(string.Format("读取外部流水号文件{0}", patchPath));
                    string[] taskIds = File.ReadAllLines(patchPath);
                    ShowMessage(string.Format("共有{0}个任务待处理", taskIds.Length - 1));
                    foreach (var item in taskIds)
                    {
                        //判断某一行是否为空行
                        if (string.IsNullOrEmpty(item) || item.ToLower().Equals("correlateid"))
                        {
                            ShowMessage("当前行数据不符合规范，将被抛弃");
                            continue;
                        }
                        string cid = item.Trim().Replace("\"", "");
                        Thread thread = new Thread(delegate () { NotifyXml(cspid, lspid, tempXmlPath, cid, pushUrl, int.Parse(pushResult), soapXml); })
                        { Name = "notifytask", IsBackground = true };
                        thread.Start();

                        //Thread.Sleep(30*1000); //休眠30秒
                    }
                }
                else
                {
                    ShowPopTips("外部批量流水号文件地址不存在，请检查！");
                }
            }
        }

        private void btnNotify_Click(object sender, EventArgs e)
        {
            string pushUrl = txtSoapUrl.Text;
            string cspid = txtCSPID.Text;
            string lspid = txtLSPID.Text;

            string correlateId = txtCorrelateId.Text; // ;getLongId().ToString()
            string pushResult = txtResult.Text;
            string soapXml = txtFtpurl.Text;
            string tmpXml = txtTemplate.Text;
            string tempXmlPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, tmpXml);
            
            Task.Run(delegate () { NotifyXml(cspid, lspid, tempXmlPath, correlateId.Trim(), pushUrl, int.Parse(pushResult), soapXml); });

        }
    }
}
